<?php

namespace common\curl;

class Curl
{
    public function get($url, $timeout = 30,$cookie='')
    {
        //echo '<br/>'.$url;
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        if(!empty($cookie))
            curl_setopt($oCurl, CURLOPT_COOKIE, $cookie);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_FOLLOWLOCATION, 1);
        //curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, 1);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, $timeout);

        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    public function post($url, $data = '', $method = 'POST', $cookieFile = '', $headers = '', $connectTimeout = 30, $readTimeout = 30)
    {
        //echo $data.'<br/>';
        $method = strtoupper($method);
        if (!function_exists('curl_init'))
            return null; //socketRequest($url, $data, $method, $cookieFile, $connectTimeout);
        $option = array(
            CURLOPT_URL => $url,
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_CONNECTTIMEOUT => $connectTimeout,
            CURLOPT_TIMEOUT => $readTimeout
        );
        if ($headers) $option[CURLOPT_HTTPHEADER] = $headers;
        if ($cookieFile) {
            $option[CURLOPT_COOKIEJAR] = $cookieFile;
            $option[CURLOPT_COOKIEFILE] = $cookieFile;
        }
        if ($data && strtolower($method) == 'post') {
            $option[CURLOPT_POST] = 1;
            $option[CURLOPT_POSTFIELDS] = $data;
        }
        if (stripos($url, 'https://') !== false) {
            $option[CURLOPT_SSL_VERIFYPEER] = false;
            $option[CURLOPT_SSL_VERIFYHOST] = false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt_array($ch, $option);
        $response = curl_exec($ch);
        $info = curl_getinfo($ch);
        if (curl_errno($ch) > 0) {
            return false;
        }
        curl_close($ch);
        if ($info['http_code'] != '200') {

        }

        return $response;
    }
}

